//
//  GoodsDisplayViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/12.
//  Copyright (c) 2015年 zhixiao. All rights reserved.
//

import UIKit
enum DisplayModel{
    case NS_Model_List,NS_Model_Grid,None
}
class GoodsDisplayViewController: BaseViewController {
    var searchBar:UISearchBar!
    var styleSwitchButton:UIButton!
    var displayTable:UITableView!
    var menuView:UIView!
    var tableDataSource:[GoodDetailItem] = []
    var categoryName:String?
    var orderitem:String  = ""
    var displayModel:DisplayModel = DisplayModel.NS_Model_Grid{
        didSet{
            switch displayModel{
            case DisplayModel.NS_Model_List:
//                styleSwitchButton.setTitle("表格", forState: UIControlState.Normal)
                styleSwitchButton.setImage(UIImage(named: "thumbnail"), forState: UIControlState.Normal)
            case DisplayModel.NS_Model_Grid:
//                styleSwitchButton.setTitle("列表", forState: UIControlState.Normal)
                styleSwitchButton.setImage(UIImage(named: "top-bar-icon"), forState: UIControlState.Normal)

            default:
                break
            }
            self.displayTable.reloadData()
        }
    }
    var currentNumber:NSInteger = 0
    var totalNumber:NSInteger = 0
    var currentPage:NSInteger = 1
    var selectButton:CommonButton?
    let length:NSInteger = 12
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupTopView()
        self.setupMenuView()
        self.createTableView()
        displayModel = DisplayModel.NS_Model_Grid
        self.displayTable.header.beginRefreshing()
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func setupMenuView()->Void{
         menuView = UIView(frame: CGRectMake(0, 64, view.bounds.size.width, 40))
        menuView.backgroundColor = UIColor.whiteColor()
        var menuButton:CommonButton?
        
        let width:CGFloat = menuView.bounds.size.width/3.0
        let height:CGFloat = menuView.bounds.height;
        let titleArray:[String] = ["综合","销量","价格"]
        for i in 0...2{
            menuButton = CommonButton(frame: CGRectMake(width*CGFloat(i)+10, 0, width-20, height))
            menuButton?.backgroundColor = UIColor.clearColor()
            menuButton?.setTitle(titleArray[i], forState: UIControlState.Normal)
//            menuButton?.setImage(UIImage(named: "back_icon"), forState: UIControlState.Normal)
            menuButton?.setTitleColor(commonRedColor, forState: UIControlState.Selected)
            menuButton?.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            menuButton?.titleLabel?.font = UIFont.systemFontOfSize(14)
            menuButton?.titleLabel?.textAlignment = NSTextAlignment.Center
            menuButton?.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            menuView.addSubview(menuButton!)
            menuButton?.tag = i
            menuButton?.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
            if i == 0{
                self.buttonClick(menuButton!)
            }
        }
        view.addSubview(menuView)
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        displayTable = UITableView(frame: CGRectMake(0, CGRectGetMaxY(menuView.frame)+10, view.bounds.size.width, view.bounds.size.height-CGRectGetMaxY(menuView.frame)-10), style: UITableViewStyle.Plain)
        displayTable.backgroundColor = UIColor.clearColor();
        displayTable.separatorStyle = UITableViewCellSeparatorStyle.None
        displayTable.showsHorizontalScrollIndicator = false
        displayTable.showsVerticalScrollIndicator = false
        displayTable.dataSource = self
        displayTable.delegate = self
        let nib = UINib(nibName:"GoodsGridCell", bundle: nil)
        displayTable.registerNib(nib, forCellReuseIdentifier:"GoodsGridCellID")
        let nib2 = UINib(nibName:"GoodsListCell", bundle: nil)
        displayTable.registerNib(nib2, forCellReuseIdentifier:"GoodsListCellID")
        displayTable.header =  MJRefreshNormalHeader(refreshingBlock:{[weak self] in
                self?.currentNumber = 0
                self?.currentPage = 1
            self?.queryGoodsByCategoryNew(self!.categoryName, offset:self!.currentPage, length:self!.length,orderitem:self!.orderitem)
            }
        )
        displayTable.footer =  MJRefreshAutoNormalFooter(refreshingBlock:{[weak self] in
                self?.currentPage++
            self?.queryGoodsByCategoryNew(self!.categoryName, offset:self!.currentPage, length:self!.length,orderitem:self!.orderitem)
            }
        )
        displayTable.footer.hidden = true
        view.addSubview(displayTable)
    }
    func buttonClick(button:UIButton){
        if button == selectButton{
            return
        }
        button.selected = true
        selectButton?.selected = false
        selectButton = button as? CommonButton
        switch selectButton!.tag{
        case 0:
            self.orderitem = ""
        case 1:
            self.orderitem = "salestotal"
        case 2:
            self.orderitem = "price"
        default:break
        }
        self.currentNumber = 0
        self.currentPage = 0
        if displayTable != nil && displayTable.header != nil{
            displayTable.header.beginRefreshing()
        }
    }
    func setupTopView(){
        //237,63,88
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
//        let topView = UIView(frame: CGRectMake(0, 0, view.bounds.size.width, topViewHeight))
//        topView.backgroundColor = commonRedColor
//        view.addSubview(topView)
        
        searchBar = UISearchBar(frame: CGRectMake(10, 22, view.bounds.size.width-10-40, 40))
        searchBar.searchBarStyle = UISearchBarStyle.Prominent
        searchBar.placeholder = "女神新装"
        searchBar.delegate = self 
        if let aview = searchBar.subviews[0] as? UIView{
            if aview.subviews.count>0{
                aview.subviews[0].removeFromSuperview()
            }
        }
        self.navigationItem.titleView = searchBar
        
        styleSwitchButton = UIButton(frame: CGRectMake(0, 0, 40, 44))
        styleSwitchButton.titleLabel?.font = UIFont.boldSystemFontOfSize(14)
        styleSwitchButton.titleLabel?.textAlignment = NSTextAlignment.Center
        styleSwitchButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        styleSwitchButton.addTarget(self, action: "changeDisplayModel", forControlEvents: UIControlEvents.TouchUpInside)
//        styleSwitchButton.setImage(UIImage(named:"TabBar1"), forState: UIControlState.Normal)
        styleSwitchButton.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: styleSwitchButton)
    }
    func queryGoodsByCategoryNew(category:String!,offset:Int,length:Int,orderitem:String)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(category, forKey: "category")
         parameters.setObject(orderitem, forKey: "orderitem")
        parameters.setObject(NSNumber(integer: offset),forKey: "c")
        parameters.setObject(NSNumber(integer:length), forKey: "s")
        request.requestStart("/plp/getproductsnew", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let array = dic?.pareseDataToGoodListArray(){
                    let total:NSString = dic?["data"]?["productCount"] as! NSString
                    self.totalNumber = total.integerValue
                    if self.currentNumber == 0{
                        self.tableDataSource.removeAll(keepCapacity: false)
                        self.tableDataSource = array
                    }
                    else{
                        for i in 0..<array.count{
                            let obj:GoodDetailItem = array[i]
                            self.tableDataSource.append(obj)
                        }
                    }
                    self.currentNumber = self.tableDataSource.count
                }
                dispatch_async(dispatch_get_main_queue()){
                    self.displayTable.reloadData()
                     self.displayTable.header.endRefreshing()
                    if self.currentNumber == self.totalNumber{
                        self.displayTable.footer.noticeNoMoreData()
                    }
                    else{
                        self.displayTable.footer.resetNoMoreData()
                    }
                    if self.displayTable.contentSize.height<self.displayTable.bounds.size.height{
                        self.displayTable.footer.hidden = true
                    }
                    else{
                        self.displayTable.footer.hidden = false
                    }
                }

            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    self.displayTable.header.endRefreshing()
                }
            }

        })
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    func changeDisplayModel(){
        if displayModel == DisplayModel.NS_Model_Grid{
            displayModel = DisplayModel.NS_Model_List
        }
        else{
            displayModel = DisplayModel.NS_Model_Grid
        }
    }
}
extension GoodsDisplayViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if displayModel == DisplayModel.NS_Model_List{
            return  self.tableDataSource.count
        }
        else{
            if tableDataSource.count%2 == 0{
                return tableDataSource.count/2
            }
            else{
                return tableDataSource.count/2 + 1
            }
        }
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        if displayModel == DisplayModel.NS_Model_List{
            let cell = tableView.dequeueReusableCellWithIdentifier("GoodsListCellID", forIndexPath: indexPath) as! GoodsListCell
            let obj:GoodDetailItem? = tableDataSource[indexPath.row]
            cell.goodsImageView.setImageWithUrl(obj!.image!,defaultImage: nil)
            cell.nameLbl.text = obj?.name
            cell.priceLbl.text = "¥"+obj!.price!
            cell.niceLbl.text = "好评100%(2000人)"
            return cell;
        }
        else{
            let cell = tableView.dequeueReusableCellWithIdentifier("GoodsGridCellID", forIndexPath: indexPath) as! GoodsGridCell
            //        cell.wineImageView.image = imageArray[indexPath.row].0
            cell.indexPath = indexPath
            var obj1,obj2:GoodDetailItem?
            obj1 = tableDataSource[indexPath.row*2]
            if indexPath.row*2+1 < tableDataSource.count{
                obj2 = tableDataSource[indexPath.row*2+1]
            }
            cell.imageView1.setImageWithUrl(obj1!.image!, defaultImage:nil)
            cell.name1.text = obj1?.name
            cell.price1.text = "¥"+obj1!.price!
            if obj2 == nil{
                cell.cell2.hidden = true
            }
            else{
                cell.imageView2.setImageWithUrl(obj2!.image!, defaultImage:nil)
                cell.name2.text = obj2?.name
                cell.price2.text = "¥"+obj2!.price!
            }
            
            cell.btnHandle = {[weak self] indexPath,buttonIndex in
                print("第\(indexPath!.row)个cell,第\(buttonIndex)个按钮")
//                                self?.selectObj = self?.rightMenuSource[indexPath!.row*2+buttonIndex]
                let ctl = GoodsDetailViewController()
                let obj:GoodDetailItem = (self?.tableDataSource[indexPath!.row*2+buttonIndex])!
                ctl.goodsID = obj.id
                ctl.hidesBottomBarWhenPushed = true
                self?.navigationController?.pushViewController(ctl, animated: true)
            }
            return cell;
        }
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        if displayModel == DisplayModel.NS_Model_List{
            return 100
        }
        else{
            return 200
        }
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        searchBar.resignFirstResponder()
        if displayModel == DisplayModel.NS_Model_List{
            let ctl = GoodsDetailViewController()
            let obj:GoodDetailItem = self.tableDataSource[indexPath.row]
            ctl.goodsID = obj.id
            ctl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctl, animated: true)
        }
        else{
            let ctl = GoodsDetailViewController()
            ctl.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(ctl, animated: true)
        }
    }
    func scrollViewDidScroll(scrollView: UIScrollView){
        searchBar.resignFirstResponder()
    }
}
extension GoodsDisplayViewController:UISearchBarDelegate{
    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool{
        searchBar.resignFirstResponder()
        let ctl = SearchViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
        return false
    }
}